<script setup lang="ts">
import { computed, ref, watchEffect } from "vue-demi";

type TargetElement = HTMLInputElement | HTMLTextAreaElement;
const props = defineProps(["modelValue"]);
const emit = defineEmits([
  "update:modelValue",
  "clear",
  "change",
  "focus",
  "blur",
]);

const inputValue = ref(props.modelValue);
const inputRef = ref<HTMLInputElement | null>(null);

watchEffect(() => {
  if (typeof props.modelValue !== "undefined") {
    inputValue.value = props.modelValue + "";
    emit("change", inputValue.value);
  }
});

const showClose = computed(() => {
  if (inputValue.value) {
    return inputValue.value.trim().length > 0;
  } else {
    return false;
  }
});

const onInput = (event: Event) => {
  let { value } = event.target as TargetElement;
  emit("update:modelValue", value);
};

const onClear = () => {
  emit("update:modelValue", "");
  emit("clear");
  inputRef.value?.focus();
};

const onFocus = () => {
  emit("focus");
};

const onBlur = () => {
  emit("blur");
};
</script>

<template>
  <div class="input-container">
    <SvgIcon icon="search" className="u-svg-search"></SvgIcon>
    <input
      ref="inputRef"
      class="input"
      type="text"
      :value="inputValue"
      @input="onInput"
      @focus="onFocus"
      @blur="onBlur"
    />
    <div class="close">
      <SvgIcon
        icon="close"
        className="u-svg-close"
        color="#666"
        v-if="showClose"
        @click.stop="onClear"
      ></SvgIcon>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.input-container {
  position: relative;
  height: 60px;
  line-height: 60px;
  padding: 0 60px;
  overflow: hidden;
  border-radius: 64px;
  background: #ebecec;

  .u-svg-search {
    position: absolute;
    left: 0;
    top: 18px;
    margin: 0 16px;
    vertical-align: middle;
  }

  .close {
    position: absolute;
    right: 0;
    top: 0;
    width: 60px;
    height: 60px;
    line-height: 56px;
    text-align: center;
  }

  .u-svg-close {
    display: inline-block;
  }

  .input {
    width: 100%;
    height: 60px;
    line-height: 36px;
    background: rgba(0, 0, 0, 0);
    font-size: 28px;
    color: #333;
  }
}
</style>
